using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Traceability.API.Models;
using Traceability.API.Services;

namespace Traceability.API.Controllers
{
    /// <summary>
    /// 文件上传控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    // [Authorize] // 暂时注释掉用于测试
    public class FileUploadController : ControllerBase
    {
        private readonly IQiNiuService _qiNiuService;
        private readonly ILogger<FileUploadController> _logger;

        public FileUploadController(IQiNiuService qiNiuService, ILogger<FileUploadController> logger)
        {
            _qiNiuService = qiNiuService;
            _logger = logger;
        }

        /// <summary>
        /// 上传单个文件
        /// </summary>
        /// <param name="file">文件</param>
        /// <param name="key">自定义文件Key(可选)</param>
        /// <returns>上传结果</returns>
        [HttpPost("upload")]
        public async Task<ActionResult<QiNiuUploadResponse>> UploadFile(IFormFile file, [FromQuery] string? key = null)
        {
            try
            {
                if (file == null || file.Length == 0)
                {
                    return BadRequest(new QiNiuUploadResponse
                    {
                        Success = false,
                        Message = "请选择要上传的文件"
                    });
                }

                var result = await _qiNiuService.UploadFileAsync(file, key);
                
                if (result.Success)
                {
                    _logger.LogInformation("文件上传成功: {FileName} -> {Key}", file.FileName, result.Key);
                    return Ok(result);
                }
                else
                {
                    _logger.LogWarning("文件上传失败: {FileName} - {Message}", file.FileName, result.Message);
                    return BadRequest(result);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "文件上传异常: {FileName}", file?.FileName);
                return StatusCode(500, new QiNiuUploadResponse
                {
                    Success = false,
                    Message = "服务器内部错误"
                });
            }
        }

        /// <summary>
        /// 批量上传文件
        /// </summary>
        /// <param name="files">文件列表</param>
        /// <returns>上传结果列表</returns>
        [HttpPost("upload-batch")]
        public async Task<ActionResult<List<QiNiuUploadResponse>>> UploadFiles(List<IFormFile> files)
        {
            try
            {
                if (files == null || !files.Any())
                {
                    return BadRequest(new { Message = "请选择要上传的文件" });
                }

                var results = new List<QiNiuUploadResponse>();

                foreach (var file in files)
                {
                    if (file != null && file.Length > 0)
                    {
                        var result = await _qiNiuService.UploadFileAsync(file);
                        results.Add(result);
                        
                        if (result.Success)
                        {
                            _logger.LogInformation("批量上传文件成功: {FileName} -> {Key}", file.FileName, result.Key);
                        }
                        else
                        {
                            _logger.LogWarning("批量上传文件失败: {FileName} - {Message}", file.FileName, result.Message);
                        }
                    }
                }

                return Ok(results);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量文件上传异常");
                return StatusCode(500, new { Message = "服务器内部错误" });
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="key">文件Key</param>
        /// <returns>删除结果</returns>
        [HttpDelete("delete/{key}")]
        public async Task<ActionResult<QiNiuDeleteResponse>> DeleteFile(string key)
        {
            try
            {
                if (string.IsNullOrEmpty(key))
                {
                    return BadRequest(new QiNiuDeleteResponse
                    {
                        Success = false,
                        Message = "文件Key不能为空"
                    });
                }

                var result = await _qiNiuService.DeleteFileAsync(key);
                
                if (result.Success)
                {
                    _logger.LogInformation("文件删除成功: {Key}", key);
                    return Ok(result);
                }
                else
                {
                    _logger.LogWarning("文件删除失败: {Key} - {Message}", key, result.Message);
                    return BadRequest(result);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "文件删除异常: {Key}", key);
                return StatusCode(500, new QiNiuDeleteResponse
                {
                    Success = false,
                    Message = "服务器内部错误",
                    Key = key
                });
            }
        }

        /// <summary>
        /// 获取上传Token
        /// </summary>
        /// <param name="key">文件Key(可选)</param>
        /// <returns>上传Token</returns>
        [HttpGet("token")]
        public ActionResult<QiNiuTokenResponse> GetUploadToken([FromQuery] string? key = null)
        {
            try
            {
                var result = _qiNiuService.GetUploadToken(key);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取上传Token异常");
                return StatusCode(500, new { Message = "服务器内部错误" });
            }
        }

        /// <summary>
        /// 获取文件访问URL
        /// </summary>
        /// <param name="key">文件Key</param>
        /// <returns>文件URL</returns>
        [HttpGet("url/{key}")]
        public ActionResult<string> GetFileUrl(string key)
        {
            try
            {
                if (string.IsNullOrEmpty(key))
                {
                    return BadRequest("文件Key不能为空");
                }

                var url = _qiNiuService.GetFileUrl(key);
                return Ok(new { Url = url });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取文件URL异常: {Key}", key);
                return StatusCode(500, new { Message = "服务器内部错误" });
            }
        }

        /// <summary>
        /// 验证文件
        /// </summary>
        /// <param name="file">文件</param>
        /// <returns>验证结果</returns>
        [HttpPost("validate")]
        public ActionResult ValidateFile(IFormFile file)
        {
            try
            {
                var (isValid, message) = _qiNiuService.ValidateFile(file);
                return Ok(new { IsValid = isValid, Message = message });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "文件验证异常");
                return StatusCode(500, new { Message = "服务器内部错误" });
            }
        }

        /// <summary>
        /// 测试接口
        /// </summary>
        /// <returns>测试结果</returns>
        [HttpGet("test")]
        public ActionResult Test()
        {
            return Ok(new { Message = "FileUpload API is working!", Time = DateTime.Now });
        }
    }
}
